<template>
  <div>
    <div class="toolbar">
      <button @click="openImageUpload">Upload Image</button>
    </div>
    <div class="tiptap-editor">
      <EditorContent :editor="editor" />
    </div>
    <input
      type="file"
      ref="fileInput"
      style="display: none"
      @change="handleImageUpload"
    />
  </div>
</template>

<script>
import { Editor, EditorContent } from '@tiptap/vue-3';
import { StarterKit } from '@tiptap/starter-kit';
import { Image } from '@tiptap/extension-image';

export default {
  components: {
    EditorContent,
  },
  setup() {
    const editor = new Editor({
      extensions: [StarterKit, Image],
      content: '<p>Upload images here!</p>',
    });

    const openImageUpload = () => {
      document.querySelector('input[type="file"]').click();
    };

    const handleImageUpload = async event => {
      const file = event.target.files[0];
      if (!file) return;

      const reader = new FileReader();
      reader.onload = () => {
        const url = reader.result;
        editor.chain().focus().setImage({ src: url }).run();
      };
      reader.readAsDataURL(file);
    };

    return {
      editor,
      openImageUpload,
      handleImageUpload,
    };
  },
};
</script>

<style>
/* 自定义样式 */
.toolbar {
  margin-bottom: 10px;
}

.toolbar button {
  padding: 5px 10px;
}
</style>
